package com.abel.quiz.services.impl;

import com.abel.quiz.dao.AuthResourcePoDao;
import com.abel.quiz.dao.AuthRolePoDao;
import com.abel.quiz.dao.BaseDao;
import com.abel.quiz.dao.RelRoleResourcePoDao;
import com.abel.quiz.po.*;
import com.abel.quiz.services.AuthResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author abel.lin
* @date_time 2017-08-04 13:57
* @description
*/
@Service
public class AuthResourceServiceImpl
    extends BaseServiceImpl<BaseDao<AuthResourcePo,AuthResourcePoCriteria>,AuthResourcePo,AuthResourcePoCriteria>
    implements AuthResourceService {

    @Autowired
    private AuthResourcePoDao authResourcePoDao;
    @Autowired
    private AuthRolePoDao authRolePoDao;
    @Autowired
    private RelRoleResourcePoDao roleResourcePoDao;

    public AuthResourceServiceImpl(){
        super.baseMapper = authResourcePoDao;
    }

    public Map<String,List<AuthRolePo>> getAllResourceRole(){
        Map<String,List<AuthRolePo>> resultMap = new HashMap<String,List<AuthRolePo>>();

        AuthResourcePoCriteria secResourceModelExample = new AuthResourcePoCriteria();
        List<AuthResourcePo> resourceList = authResourcePoDao.selectByExample(secResourceModelExample);

        if(resourceList != null && resourceList.size() > 0){
            for(AuthResourcePo secResourceModel : resourceList){
                AuthRolePoCriteria roleCriteria = new AuthRolePoCriteria();
                roleCriteria.createCriteria().andIdIn(getRoleIdsByResourceId(secResourceModel.getId()));
                List<AuthRolePo> roleList = authRolePoDao.selectByExample(roleCriteria);
                resultMap.put(secResourceModel.getValue(), roleList);

            }
        }

        return resultMap;
    }

    public List<String> getRoleIdsByResourceId(String resourceId){
        List<String> roleIds = new ArrayList<String>();

        RelRoleResourcePoCriteria criteria = new RelRoleResourcePoCriteria();
        criteria.createCriteria().andResourceIdEqualTo(resourceId);
        List<RelRoleResourcePo> list = roleResourcePoDao.selectByExample(criteria);
        if(list != null && list.size() > 0){
            for(RelRoleResourcePo model : list){
                roleIds.add(model.getRoleId());
            }
        }

        HashSet<String> h  =   new  HashSet<String>(roleIds);
        roleIds.clear();
        roleIds.addAll(h);
        return roleIds;
    }

}
